//
//  HMUserAccountViewModel.swift
//  HMWeibo1
//
//  Created by liGordon on 16/4/11.
//  Copyright © 2016年 lifuli. All rights reserved.
//

import UIKit


/// 专门处理 HMUserAccount 模型相关操作,网络请求,字典转模型,归解档

class HMUserAccountViewModel: NSObject {

    // 单例
    static let sharedInstance = HMUserAccountViewModel()
    
    private override init() {
        super.init()
        
        
        // 单例的init只执行了一次
        // 加载账号
        userAccount = loadUserAccount()
    }
    
    
    /// 账号模型,只要拿到单例就可以访问到,全局通用
    var userAccount: HMUserAccount?
    
    
    
    /// 用户是否登录
    var userLogin: Bool {
        get {
            return userAccount != nil
        }
    }
    
    
    
    
    
    /// 获取accessToken
    func loadAccessToken(code: String, loadAccessTokenCallback: (error: NSError?) -> ()) {
        // 1.urlString
        let urlString = accessTokenURLString
        
        // 2.参数,字典
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": grant_type,
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        /// 放请求 afn.POST
        HMNetwork.shareInstance.POST(urlString, parameters: parameters, progress: nil, success: { (task , responseObject) -> Void in
            
            // as: 表示类型转换
            // as?: 有可能转成功,有可能转失败
            // as!: 一定能转成功 如果转换失败 直接挂了
            
            let result = responseObject as? [String: AnyObject]
            
            if let dict = result {
                // 字典转模型, 并给属性赋值
                self.userAccount = HMUserAccount(dict: dict)
                self.saveUserAccount()
                
                // 通知控制器账号加载完成了调用闭包
                loadAccessTokenCallback(error:nil)
            }
            
            }) { (task, error) -> Void in
                loadAccessTokenCallback(error: error)
        }
    }
    
    /// 保存账号模型
    private func saveUserAccount() {
        HMPrint("accountPath: \(accountPath)")
        
        if let userAccount = self.userAccount {
            // 归档
            NSKeyedArchiver.archiveRootObject(userAccount, toFile: accountPath)
        }
    }
    
    /// 从沙盒里面解档userAccount对象
    func loadUserAccount() -> HMUserAccount? {
        
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? HMUserAccount
        // 可选绑定
        if let account = userAccount where account.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            HMPrint("没有过期: \(account)")
            return account
        }
        
        return nil
        
    }
    

    
    
    /// Mark  - 获取用户信息 (access_token  UID)
    
    func loadUserInfo(loadUserInfoCallback: (error: NSError?) -> ()) {
        
        guard let access_token = userAccount?.access_token else {
            // 能进来表示 userAccount? 没有值,或者access_token的值
            HMPrint("userAccount?没有值, 或access_token咩有值")
            return
        }
        
        
        guard let uid = userAccount?.uid else {
            HMPrint("userAccount?没有值, 或uid咩有值")
            return
        }
        
        
        // url
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        // 参数
        let parameters = [
            "access_token" : access_token,
            "uid" : uid
        ]
        
        
        HMNetwork.shareInstance.GET(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
             HMPrint("加载用户信息成功: \(responseObject)")
            if let dict = responseObject as? [String: AnyObject]{
                // 将获取到的数据赋值给当前账号
                self.userAccount?.screen_name = dict["screen_name"] as? String
                self.userAccount?.avatar_large = dict["avatar_large"] as? String

                // 将当前对象保存到沙盒中
                self.saveUserAccount()
                
                loadUserInfoCallback(error: nil)
                
            }
            
            }) { (task, error) -> Void in
                loadUserInfoCallback(error: error)
        }
    }
    
    
    
}

